import { useState, useEffect, useRef } from "react";

export default function Subtitle({ items }) {
    const [subtitle, setSubtitle] = useState("");
    const subtitleKey = useRef(null);
    let millisecond = 0;

    useEffect(() => {
        if (items.length === 0) {
            return;
        }

        const incrementMillisecond = () => {
            millisecond += 30;
            for (let i = 0; i < items.length; i++) {
                const element = items[i];
                if (
                    millisecond >= element.start &&
                    millisecond <= element.end
                ) {
                    setSubtitle(element.content);
                    break;
                } else {
                    setSubtitle("");
                }
            }
        };

        const timer = setInterval(incrementMillisecond, 30);

        return () => {
            clearInterval(timer);
        };
    }, []);

    return (
        subtitle && (
            <div className="absolute bottom-20 text-4xl text-center w-full">
                {subtitle}
            </div>
        )
    );
}
